package com.ry.thread.register.client;

/**
 * RegisterWorker
 *
 * @author jiangyixin
 * @version 1.0
 * @date 2021/6/30 下午5:50
 */
public class RegisterClientWorker extends Thread{
    public static final String SERVICE_NAME = "inventory-service";
    public static final String IP = "192.168.31.207";
    public static final String HOSTNAME = "inventory01";
    public static final int PORT = 9000;
    private HttpSender httpSender;
    private Boolean finishRegister;
    private final String serviceInstanceId;
    
    public RegisterClientWorker(String serviceInstanceId) {
        this.serviceInstanceId = serviceInstanceId;
        this.finishRegister = false;
        this.httpSender = new HttpSender();
    }
    
    @Override
    public void run() {
        if (!finishRegister) {
            RegisterRequest registerRequest = new RegisterRequest();
            registerRequest.setServiceName(SERVICE_NAME);
            registerRequest.setIp(IP);
            registerRequest.setHostname(HOSTNAME);
            registerRequest.setPort(PORT);
            registerRequest.setServiceInstanceId(serviceInstanceId);
            RegisterResponse registerResponse = httpSender.register(registerRequest);
            System.out.println("服务注册结果为: " + registerResponse.getStatus());
            if (!RegisterResponse.SUCCESS.equals(registerResponse.getStatus())) {
                this.finishRegister = true;
            } else {
                return;
            }
            HeartbeatRequest heartbeatRequest = new HeartbeatRequest();
            heartbeatRequest.setServiceInstanceId(serviceInstanceId);
            HeartbeatResponse heartbeatResponse = null;
            while (true) {
                try {
                    heartbeatResponse = httpSender.heartBeat(heartbeatRequest);
                    Thread.sleep(30 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
